﻿using System.Text.RegularExpressions;

namespace ExcelHelper
{
    public static class ExcelHelper
    {

        public static bool TryGetExcelColumn(string position, out int row, out int column)
        {
            position = position.ToUpper();
            row = -1;
            column = -1;

            if (!Regex.IsMatch(position, "^[A-Z]{1,}[0-9]{1,}$"))
            {
                return false;
            }

            var rowResult = Regex.Match(position, "[0-9]{1,}");

            if (rowResult.Success)
            {
                row = int.Parse(rowResult.Value);
            }
            else
            {
                return false;
            }

            var columnResult = Regex.Match(position, "[A-Z]{1,}");

            if (columnResult.Success)
            {
                column = ParseColumn(columnResult.Value);
            }
            else
            {
                return false;
            }

            return true;
        }

        private const int BaseValue = 26;

        private static int ParseColumn(string columnString)
        {
            int column = 0;
            int count = columnString.Length;

            foreach (var clumnChar in columnString)
            {
                var n = clumnChar - 'A' + 1;
                var temp = n * (int)Math.Pow(BaseValue, --count);
                column += temp;
            }

            return column;
        }
    }
}
